package com.example.tabbar.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.tabbar.R
import com.example.tabbar.adapter.UserAdapter
import com.example.tabbar.databinding.FragmentUserListBinding
import com.example.tabbar.listener.OnFragmentSwitchListener
import com.example.tabbar.utils.CustomLine
import com.junray.usermangement.room.bean.UserWithRole
import com.junray.usermangement.room.entity.User
import com.junray.usermangement.utils.SessionManager
import com.junray.usermangement.utils.SessionManager.Companion.instance
import com.junray.usermangement.viewModel.UserViewModel


class UserListFragment : Fragment() {
    private var binding: FragmentUserListBinding? = null
    private var recyclerview: RecyclerView? = null
    private var adapter: UserAdapter? = null
    private var viewModel : UserViewModel? = null
    private var sessionManager: SessionManager? = null
    private var currentUser : User? = null
    // 当前用户角色权限等级
    private var currentUserRoleLevel: Int ? =null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }
    private var listener : OnFragmentSwitchListener? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentUserListBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()

        //用户列表底部按钮
        onClick()
    }

    private fun initView() {
        viewModel = ViewModelProvider(this)[UserViewModel::class.java]
        recyclerview = binding?.usersRecyclerView
        adapter = UserAdapter()
        recyclerview?.adapter = adapter
        recyclerview?.layoutManager = LinearLayoutManager(requireContext())
        sessionManager = instance
        currentUser = sessionManager?.currentUser
        currentUserRoleLevel = sessionManager?.currentRoleLevel

        //分割线
        CustomLine(requireContext(), recyclerview!!)

        viewModel?.userWithRole?.observe(viewLifecycleOwner) { userRole: MutableList<UserWithRole>?->
            if (!userRole.isNullOrEmpty()){
                filterAndShowUsers(userRole)
            } else {
                adapter?.setItems(ArrayList())
            }
        }

        adapter?.setOnItemClickListener {userId, level ->
            val editUserFragment = EditUserFragment.newInstance(userId, level)
            listener?.onFragmentSwitch(editUserFragment)
        }
    }

    private fun onClick() {

        binding?.setUser?.setOnClickListener {
            // 欣微屏幕旋转 需重启后
//            SdkApi.getInstance().Display().setScreenRotate(ApiTool.Screen.ALL, 0)
            if (sessionManager?.currentUser != null) {
                val setUserFragment = SetUserFragment.newInstance()
                listener?.onFragmentSwitch(setUserFragment)
            } else {
                Toast.makeText(requireContext(), R.string.tb_please_login_account, Toast.LENGTH_SHORT).show()
            }
        }

        binding?.userExport?.setOnClickListener {
//            ZtlManager.GetInstance().startWifiSettings()
            val fragment1 = AccountFragment.newInstance()
            Log.d("Test", "Fragment1 hash: ${fragment1.hashCode()}")

        }
    }
    // 过滤掉比自身权限级别高的用户
    private fun filterAndShowUsers(allUsers: MutableList<UserWithRole>) {
        if (sessionManager!!.isSuperAdmin) {
            adapter?.setItems(allUsers)
            return
        }
        val filteredUsers: MutableList<UserWithRole> = ArrayList()

        val currentUserId = sessionManager!!.currentUser?.id
        val currentRoleLevel = currentUserRoleLevel ?:4

        // 根据角色级别过滤掉同级别和高级别的用户
        val levelFilteredUsers = allUsers.filter { user ->
            user.level > currentRoleLevel || (user.level == currentRoleLevel && user.userId == currentUserId)  // 同级别只显示自身
        }
        if (levelFilteredUsers.isEmpty()) {
            adapter!!.setItems(ArrayList())
            return
        }

        for (user in levelFilteredUsers) {
            filteredUsers.add(user)
        }
        val distinctUsers = filteredUsers.distinctBy { it.userId }.sortedBy { it.id }
        adapter!!.setItems(distinctUsers)

    }
    private fun setEmpty(isEmpty: Boolean) {
        binding!!.empty.root.visibility =
            (if (isEmpty) View.VISIBLE else View.GONE)
        binding!!.usersRecyclerView.visibility =
            (if (isEmpty) View.GONE else View.VISIBLE)
    }

    fun setListener(listener: OnFragmentSwitchListener) {
        this.listener = listener
    }

    companion object {
        @JvmStatic
        fun newInstance() =
            UserListFragment().apply {
                arguments = Bundle().apply {
                }
            }
    }
}

